import { RouteRecordRaw } from "vue-router"
import { IBreadcrumb } from "@/base-ui/breadcrumb"

// 将动态路由映射到 routes
export function mapMenusToRoutes(userMenus: any[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  // 1 先去加载默认所有的 routes
  const allRoutes: RouteRecordRaw[] = []
  // require.context webpack 的函数 (第一个参数是页面路径，第二个是否递归匹配所有,第三个是正则)
  const routeFiles = require.context("../router/index", true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    // 拼接路径
    const routePath = require("../router/index" + key.split(".")[1])
    routePath.default.path = routePath.default.path.replace("index", "main")
    allRoutes.push(routePath.default)
  })

  // 递归查找对应的 children
  const recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type == 2) {
        // 查找相同的路径
        const currentPath = allRoutes.find((route) => route.path === menu.url)
        if (currentPath) routes.push(currentPath)
      } else {
        recurseGetRoute(menu.children)
      }
    }
  }

  recurseGetRoute(userMenus)

  // 2 根据菜单获取需要加的 routes
  return routes
}

// 查找当前显示的面包屑
export function pathMapBreadcrumbs(userMenus: any[], currentPath: string): any {
  const breadcrumbs: IBreadcrumb[] = []
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapBreadcrumbs(menu.children, currentPath)
      if (findMenu.name) {
        breadcrumbs.push({ name: menu.name, path: menu.url })
        breadcrumbs.push({ name: findMenu.name, path: findMenu.url })
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
  return breadcrumbs
}

// 处理权限
export function mapMenusToPermissions(userMenus: any[]) {
  const permissions: string[] = []

  // 使用递归函数查找
  const _recurseGetPermission = (menus: any[]) => {
    for (const item of menus) {
      if (item.type === 1 || item.type === 2) {
        _recurseGetPermission(item.children ?? [])
      } else if (item.type === 3) {
        permissions.push(item.permission)
      }
    }
  }
  _recurseGetPermission(userMenus)
  return permissions
}
